{%extends "base.html"%}
{%block onload%}{{ block.super }}register_player_channel();{%endblock%}
{%block body%}
<script>
function on_player_message(message) {
  msg_box = document.getElementById('lastMsg')
  message = process_player_message(message.data)
  if (message) {
    $().toastmessage("showToast", {
      "text"    : message,
      "sticky"  : false,
      "type"    : "notice",
    });
  }
}

function register_player_channel() {
  var token = '{{player_token}}';
  if (!token) {
    on_player_message({data: 'Connot connect'});
    return;
  }
  var channel = new goog.appengine.Channel(token);
  player_socket = channel.open();
  player_socket.onmessage = on_player_message;
  player_socket.onerror = alert;
}

function process_player_message(message) {
  var data = message.split('|');
  var event = data[0];
  var reference = data[1];
  var detail = data[2];

{%block proccess_player_message%}{%endblock%}

  if (event.indexOf('beaten') >= 0 || event.indexOf('beat') >= 0) {
    return detail + ": " +
        '<a href="/replay?reference=' + reference + '">view replay</a>' +
        " or " +
        '<a href="/play?reference=' + reference + '">play</a>';
  } else if (event == 'friend request received') {
    update_friends();
    return detail + ": " +
        "<a href=\"javascript:dao('friends', 'accept', 'reference=" + reference + "', update_friends, alert, clear_player_message);\">accept</a>" +
        " or " +
        "<a href=\"javascript:dao('friends', 'reject', 'reference=" + reference + "', update_friends, alert, clear_player_message);\">reject</a>";
  } else if (event == 'friend request accepted' || event == 'friend alias changed' || event == 'friend removed') {
    update_friends();
  }

  return detail;
}

function clear_player_message() {
  msg_box = document.getElementById('lastMsg')
  msg_box.innerHTML = '';
}

function update_friends() {
{%block update_friends%}{%endblock%}
}

</script>
<table width="100%"><tr><td>Player: {{alias}}</td><td id=lastMsg align="right"></td></tr></table>
{%endblock%}
